package edu.ruc.cluster.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.HashMap;

public class PropertyRetrieval {
	
//	private static DefaultLogHandler logHandler = new DefaultLogHandler();
	private static DefaultLogHandler logHandler = DefaultLogHandler.getInstance();
	private File file = null;
	private Map<String, String> properties = null;
	
	private void createNewFile(){
		File parent = file.getParentFile();
		if(parent != null && parent.exists() == false)
			parent.mkdirs();
		try{
			file.createNewFile();
			logHandler.info("create new file: " + file.getAbsolutePath());
		}catch(IOException e){
			logHandler.error("Unable to create new file " + file.getAbsolutePath(), e);
		}
	}
	public PropertyRetrieval(String filename, boolean tag){
		properties = new HashMap<String, String>();
		file = new File(filename);
		if(file.exists() == false){
			createNewFile();
			return;
		}
	}
	public PropertyRetrieval(String filename){
		properties = new HashMap<String, String>();
		file = new File(filename);
		if(file.exists() == false){
			createNewFile();
			return;
		}
		BufferedReader reader = null;
		try{
			reader = new BufferedReader(new FileReader(file));
			String line = "";
			StringBuffer buffer = new StringBuffer();
			while((line = reader.readLine()) != null){
				if(line.startsWith("#"))
					continue;
				buffer.append(line + "\n");
				
			}
			for(String str : buffer.toString().split("\n")){
				String[] tokens = str.split(Const.LINE_SEPERATOR);
				if(tokens.length == 2){
					properties.put(tokens[0], tokens[1]);
				}
			}
			logHandler.info("Successfully load property information from " + filename);
		}catch(IOException e){
			logHandler.error(this.getClass().getSimpleName() + " " + e.getMessage(), e);
		}finally{
			try{
				if(reader != null)
					reader.close();
			}catch(IOException e){
				logHandler.error(this.getClass().getSimpleName() + " " + e.getMessage(), e);
			}
		}		
	}
	
	public String getString(String key){
		
		if(properties.isEmpty()){
			logHandler.error("No information got from " + file.getAbsolutePath());
			return null;
		}
		if(properties.containsKey(key))
			return properties.get(key);
		logHandler.error("No corresponding value fectched for key " + key + " in file " + file.getAbsolutePath());
		return null;
	}
	
	public void add(String key, String value){
		try{
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			long length = raf.length();
			raf.seek(length);
			raf.writeBytes(key + Const.LINE_SEPERATOR + value + "\n");
			raf.close();
			logHandler.info("Successfully add " + key + " to config file");
		}catch(IOException e){
			logHandler.error("Error in writing random access file!" + this.getClass().getSimpleName() + " " + e.getMessage(), e);
		}
	}
	
	public void putString(String key, String value){
		try{
			boolean append = true;
			String newContent = key + Const.LINE_SEPERATOR + value + "\n";
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line = null;
			StringBuffer buffer = new StringBuffer();
			while((line = reader.readLine()) != null){
				String[] strs = line.split(Const.LINE_SEPERATOR);
				if(strs[0].equals(key)){
					buffer.append(newContent);
					append = false;
				}
				else
					buffer.append(line + "\n");
			}
			if(append == true)
				buffer.append(newContent);
			reader.close();
			
			BufferedWriter writor = new BufferedWriter(new FileWriter(file));
			writor.write(buffer.toString());
			writor.close();
			logHandler.info("Successfully update " + key + " in config file");
			
		}catch(FileNotFoundException e){
			logHandler.error(this.getClass().getSimpleName() + " " + e.getMessage(), e);
		}catch(IOException e){
			logHandler.error(this.getClass().getSimpleName() + " " + e.getMessage(), e);
		}
		
		properties.put(key, value);
	}
}
